package com.bosssoft.platform.fasttcc.impl;

import com.bosssoft.platform.fasttcc.Xid;
import com.jfireframework.baseutil.StringUtil;

public class XidImpl implements Xid
{
    private byte[] globalId;
    private byte[] brachId;
    private String toString;

    @Override
    public byte[] getGlobalId()
    {
        return globalId;
    }

    @Override
    public byte[] getBranchId()
    {
        return brachId;
    }

    public void setGlobalId(byte[] globalId)
    {
        this.globalId = globalId;
    }

    public void setBrachId(byte[] brachId)
    {
        this.brachId = brachId;
    }

    @Override
    public int hashCode()
    {
        int hashcode = (((globalId[0] ^ globalId[4]) & 0xff) << 24)//
                | (((globalId[1] ^ globalId[5]) & 0xff) << 16)//
                | (((globalId[2] ^ globalId[6]) & 0xff) << 8)//
                | (((globalId[3] ^ globalId[7]) & 0xff) << 0);
        if (brachId != null)
        {
            int second = (((brachId[0] ^ brachId[4]) & 0xff) << 24)//
                    | (((brachId[1] ^ brachId[5]) & 0xff) << 16)//
                    | (((brachId[2] ^ brachId[6]) & 0xff) << 8)//
                    | (((brachId[3] ^ brachId[7]) & 0xff) << 0);
            hashcode = hashcode ^ second;
        }
        return hashcode;
    }

    @Override
    public boolean equals(Object o)
    {
        if (o instanceof Xid == false)
        {
            return false;
        }
        byte[] globalId = ((Xid) o).getGlobalId();
        for (int i = 0; i < this.globalId.length; i++)
        {
            if (this.globalId[i] != globalId[i])
            {
                return false;
            }
        }
        if (brachId == null)
        {
            if (((Xid) o).getBranchId() == null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            byte[] branchId = ((Xid) o).getBranchId();
            if (branchId == null)
            {
                return false;
            }
            for (int i = 0; i < this.brachId.length; i++)
            {
                if (this.brachId[i] != branchId[i])
                {
                    return false;
                }
            }
            return true;
        }
    }

    @Override
    public String toString()
    {
        if (toString != null)
        {
            return toString;
        }
        if (brachId != null)
        {
            StringBuilder s = new StringBuilder();
            s.append(StringUtil.toHexString(globalId)).append("-").append(StringUtil.toHexString(brachId));
            toString = s.toString();
        }
        else
        {
            StringBuilder s = new StringBuilder();
            s.append(StringUtil.toHexString(globalId));
            toString = s.toString();
        }
        return toString;
    }
}
